package com.imachen.ymcc.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.imachen.ymcc.constants.RedisSmsConstants;
import com.imachen.ymcc.domain.MessageBlack;
import com.imachen.ymcc.enums.GlobalExceptionCode;
import com.imachen.ymcc.mapper.MessageBlackMapper;
import com.imachen.ymcc.result.JSONResult;
import com.imachen.ymcc.service.IMessageBlackService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.imachen.ymcc.util.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author imachen
 * @since 2022-10-03
 */
@Service
public class MessageBlackServiceImpl extends ServiceImpl<MessageBlackMapper, MessageBlack> implements IMessageBlackService {

    @Autowired
    private RedisTemplate redisTemplate;


    // 加入黑名单
    @Override
    public JSONResult onBlack(MessageBlack messageBlack) {
        // 判断黑名单中是否有该手机号
        Wrapper<MessageBlack> wrapper = new EntityWrapper<>();
        wrapper.eq("phone",messageBlack.getPhone());
        MessageBlack black = selectOne(wrapper);
        // 如果为null 就添加到黑名单
        AssertUtil.isNull(black, GlobalExceptionCode.BLACK_ERROR);
        messageBlack.setCurrentTime(new Date());
        insert(messageBlack);

        // 将黑名单添加到redis
        List<MessageBlack> messageBlacks = selectList(null);
        // 拼接业务键
        String rediskey = String.format(RedisSmsConstants.REDIS_REGISTER_BLACK_KEY, messageBlacks);
        redisTemplate.opsForValue().set(rediskey, JSON.toJSONString(messageBlacks));
        return JSONResult.success();
    }



    // 移除黑名单
    @Override
    public JSONResult remove(Long id) {

        // 清除缓存
        List<MessageBlack> messageBlacks = selectList(null);
        String rediskey = String.format(RedisSmsConstants.REDIS_REGISTER_BLACK_KEY, messageBlacks);
        redisTemplate.delete(rediskey);

        // 删除黑名单
        Wrapper<MessageBlack> wrapper = new EntityWrapper<>();
        wrapper.eq("id",id);
        delete(wrapper);

        return JSONResult.success();
    }
}
